import { request } from '../../request/index'
import regeneratorRuntime from '../../lib/runtime/runtime';
Page({

    /**
     * 页面的初始数据
     */
    data: {
        goodsObj:{},
        isCollect:false 
    },
    /* 商品对象 */
    goodsInfo:{},/* 这里不明白，还有thisdata与setData................................................. */
    
    /* onShow不要形参 */
    onShow: function () {
        let Pages =  getCurrentPages();
        let options = Pages[Pages.length-1].options

        const {goods_id} = options
        this.getGoodsDetail(goods_id)
    },
    async getGoodsDetail(goods_id){
        const goodsObj = await request({
            url:"/goods/detail",
            data:{goods_id}
        })
        this.goodsInfo = goodsObj
        /* 获取缓存中收藏数组 */
        let collect = wx.getStorageSync("collect")||[];
        /* 判断缓存中商品是否被收藏 */
        let isCollect = collect.some(v=>v.goods_id===this.goodsInfo.goods_id)
         this.setData({
            goodsObj,isCollect
            /* 当不识别webp格式图片时，最好让后台处理，下面是前端处理方式 */
            /* goodsObj:{
                goods_name:goodsObj.goods_name
                goods_price:goodsObj.goods_price
                goods_introduce:goodsObj.goods_introduce.replace(/\.webp/g,".jpg")
                pics:goodsObj.pics
            } */
        })
    },
    /* 点击预览图片 */
    handlePreview(e){ 
        /* 构造图片数组 */
        const urls = this.goodsInfo.pics.map(v=>v.pics_mid)
        /* 接收传参 */
        const mid = e.currentTarget.dataset.url
        wx.previewImage({
            current: mid,
            urls: urls
        });
    },
    /* 点击 加入购物车 */
    handleCartAdd(){
        /* 检查购物车中是否有这个货物 */
        /* 从缓存获取是否有购物，无的话为空 */
        let cart = wx.getStorageSync("cart")||[];
        let index = cart.findIndex(v=>v.goods_id===this.goodsInfo.goods_id)
        if (index===-1) {
            this.goodsInfo.num=1
            this.goodsInfo.checked=true
            cart.push(this.goodsInfo)
        } else {
            cart[index].num++
        }
        wx.setStorageSync('cart', cart);
        wx.showToast({
            title: '加入成功',
            icon: 'success',
            mask: true,
        });
    },
    /* 点击添加收藏 */
    handleCollect(){
        let isCollect = false
        const collect = wx.getStorageSync("collect")||[]
        let index = collect.findIndex(v=>v.goods_id===this.goodsInfo.goods_id)
        if (index!==-1) {
            collect.splice(index,1)
            isCollect = false
            wx.showToast({
                title: '取消成功',
                icon: 'none',
            });
        }else{
            collect.push(this.goodsInfo)
            isCollect = true
            wx.showToast({
                title: '收藏成功',
                icon: 'none',
            });
        }
        wx.setStorageSync("collect", collect);
        this.setData({isCollect})
    }
})